from rest_framework.response import Response
from rest_framework.views import APIView
import redis
from user.views import check_user
from work.models import Good

# 购物车
class Cart(APIView):
    @check_user
    def post(self,request,payLoad):
        user_id = payLoad['id']
        good_id = request.data.get('productID')  # 商品id
        goods_info = Good.objects.filter(id=good_id).first()
        if not goods_info:
            return Response({'code':400,'msg':'商品不存在'})
        key ='cart:%s'%user_id  # 定义redis的key用来存放数据
        r = redis.Redis()
        goods_count = r.hget(key,good_id)  # 获取redis中 当前用户 当前商品 在购物车中的数量
        if not goods_count:
            r.hset(key,good_id,str(1))
            return Response({'code':200,'msg':'加入购物车ok',
                             'shoopingCartData':{
                                 "id": goods_info.id,
                                 "productID": goods_info.id,
                                 "productName": goods_info.sku_name,
                                 "productImg": goods_info.img,
                                 "price": goods_info.selling_price,
                                 'num': 1,
                                 'maxNum': goods_info.stock,
                                 'check': True,
                             }})
        else:
            r.hincrby(key,good_id)
            return Response({
                'code':201,'msg':'商品已经在购物车，数量加1'
            })

    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        key = 'cart:%s'%user_id
        r = redis.Redis()
        good_list = r.hgetall(key)
        select_key = 'cart_select:%s'%user_id
        select_good = r.smembers(select_key)
        check_all = []
        for i in select_good:
            check_all.append(int(i.decode()))
        print(check_all)
        cart_all = []
        for key,val in good_list.items():
            good_id = int(key.decode())
            goods_count = int(val.decode())
            goods_info = Good.objects.filter(id=good_id).first()
            if not goods_info:
                continue
            check = False
            if goods_info.id in check_all:
                check = True
            cart_all.append({
                'id': goods_info.id,
                'productID': goods_info.id,
                'productName': goods_info.sku_name,
                'productImg': goods_info.img,
                'price': goods_info.selling_price,
                'num': goods_count,
                'maxNum': goods_info.stock,
                'check': check,
            })
        return Response({
            'code':200,'msg':'购物车数据获取成功',
            'shoppingCartData':cart_all
        })

    @check_user
    def put(self,request,payload):
        user_id = payload['id']
        goods_id = request.data.get('productID')
        num = request.data.get('num')
        good_info = Good.objects.filter(id=goods_id).first()
        if not good_info:
            return Response({"code": 400,"msg": "该商品不存在"})
        if good_info.stock < num:
            return Response({"code": 400,"msg": "库存不足"})
        r = redis.Redis()
        key = "cart:%s" % user_id
        try:
            r.hset(key, goods_id, num)
            return Response({
                "code": 200,"msg": "修改购物车数量成功，当前数量%s" % num
            })
        except:
            return Response({
                "code": 400,"msg": "修改购物车数量失败"
            })

    @check_user
    def delete(self,request,paload):
        user_id = paload['id']
        good_id = request.data.get('projectID')
        r = redis.Redis()
        key = 'cart%s'%user_id
        r.hdel(key,good_id)
        return Response({
            'code':200,'msg':'删除成功'
        })


